<template>
  <view class="order-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">订单录入</text>
      <text class="page-subtitle">输入有效订单号获取抽奖次数</text>
    </view>

    <!-- 订单输入卡片 -->
    <view class="card order-input-card">
      <view class="input-section">
        <view class="input-label">
          <text class="label-text">订单号</text>
          <text class="label-tip">请输入或粘贴您的订单号</text>
        </view>
        <view class="input-container">
          <input 
            class="order-input" 
            v-model="orderNumber" 
            placeholder="请输入订单号" 
            maxlength="50"
            @input="onInputChange"
          />
          <button class="paste-btn" @tap="pasteOrderNumber">
            <text class="paste-text">粘贴</text>
          </button>
        </view>
      </view>
      
      <view class="submit-section">
        <button 
          class="submit-btn" 
          :class="{ 'btn-disabled': !canSubmit }"
          @tap="submitOrder"
          :disabled="!canSubmit"
        >
          <text class="submit-text">{{ submitLoading ? '验证中...' : '提交验证' }}</text>
        </button>
      </view>
    </view>

    <!-- 历史记录 -->
    <view class="card history-card" v-if="orderHistory.length > 0">
      <view class="history-header">
        <text class="history-title">历史记录</text>
        <text class="history-count">共{{ orderHistory.length }}条</text>
      </view>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in orderHistory" 
          :key="index"
        >
          <view class="history-info">
            <text class="history-order">{{ item.orderNumber }}</text>
            <text class="history-time">{{ formatTime(item.createTime) }}</text>
          </view>
          <view class="history-result">
            <text 
              class="result-text" 
              :class="item.status === 'success' ? 'success' : 'failed'"
            >
              {{ item.status === 'success' ? `+${item.lotteryCount}次` : '无效订单' }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 说明信息 -->
    <view class="card info-card">
      <view class="info-header">
        <text class="info-title">📋 订单录入说明</text>
      </view>
      <view class="info-content">
        <text class="info-item">• 每个有效订单号可获得1-3次抽奖机会</text>
        <text class="info-item">• 同一订单号只能使用一次</text>
        <text class="info-item">• 订单号需要是近30天内的有效订单</text>
        <text class="info-item">• 系统将自动验证订单的有效性</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const orderNumber = ref('')
const submitLoading = ref(false)
const orderHistory = ref([])

// 计算属性
const canSubmit = computed(() => {
  return orderNumber.value.trim().length >= 6 && !submitLoading.value
})

// 输入变化处理
const onInputChange = (e) => {
  orderNumber.value = e.detail.value.trim()
}

// 粘贴订单号
const pasteOrderNumber = async () => {
  try {
    const clipboardData = await uni.getClipboardData()
    if (clipboardData.data) {
      orderNumber.value = clipboardData.data.trim()
      uni.showToast({
        title: '粘贴成功',
        icon: 'success',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('粘贴失败:', error)
    uni.showToast({
      title: '粘贴失败',
      icon: 'none'
    })
  }
}

// 提交订单验证
const submitOrder = async () => {
  if (!canSubmit.value) return
  
  submitLoading.value = true
  
  try {
    // 调用后端API验证订单
    // const res = await api.verifyOrder({
    //   orderNumber: orderNumber.value
    // })
    
    // 模拟API调用
    await mockVerifyOrder()
    
  } catch (error) {
    console.error('订单验证失败:', error)
    uni.showToast({
      title: '验证失败，请重试',
      icon: 'none'
    })
  } finally {
    submitLoading.value = false
  }
}

// 模拟订单验证
const mockVerifyOrder = async () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟验证结果
      const isValid = Math.random() > 0.3 // 70%概率有效
      const lotteryCount = isValid ? Math.floor(Math.random() * 3) + 1 : 0
      
      const result = {
        orderNumber: orderNumber.value,
        status: isValid ? 'success' : 'failed',
        lotteryCount: lotteryCount,
        createTime: Date.now()
      }
      
      // 添加到历史记录
      orderHistory.value.unshift(result)
      saveOrderHistory()
      
      if (isValid) {
        // 更新抽奖次数
        const currentCount = uni.getStorageSync('lotteryCount') || 0
        const totalCount = uni.getStorageSync('totalLotteryCount') || 0
        uni.setStorageSync('lotteryCount', currentCount + lotteryCount)
        uni.setStorageSync('totalLotteryCount', totalCount + lotteryCount)
        
        uni.showModal({
          title: '验证成功',
          content: `恭喜您获得${lotteryCount}次抽奖机会！`,
          showCancel: false,
          success: () => {
            orderNumber.value = ''
          }
        })
      } else {
        uni.showModal({
          title: '验证失败',
          content: '订单号无效或已使用过，请检查后重试',
          showCancel: false
        })
      }
      
      resolve(result)
    }, 2000)
  })
}

// 加载历史记录
const loadOrderHistory = () => {
  const history = uni.getStorageSync('orderHistory') || []
  orderHistory.value = history
}

// 保存历史记录
const saveOrderHistory = () => {
  uni.setStorageSync('orderHistory', orderHistory.value)
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

// 生命周期钩子
onLoad(() => {
  loadOrderHistory()
})
</script>

<style scoped>
.order-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
  padding-bottom: 100px;
}

/* 页面标题 */
.page-header {
  padding: 30px 20px 20px;
  text-align: center;
}

.page-title {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #FFB800;
  margin-bottom: 8px;
}

.page-subtitle {
  display: block;
  font-size: 14px;
  color: #666;
}

/* 订单输入卡片 */
.order-input-card {
  margin: 20px 16px;
}

.input-section {
  margin-bottom: 24px;
}

.input-label {
  margin-bottom: 12px;
}

.label-text {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.label-tip {
  display: block;
  font-size: 12px;
  color: #999;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-input {
  flex: 1;
  padding: 14px 16px;
  border: 2px solid #FFE082;
  border-radius: 12px;
  font-size: 16px;
  background: white;
  transition: border-color 0.3s ease;
}

.order-input:focus {
  border-color: #FFB800;
}

.paste-btn {
  background: #FFB800;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px 16px;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.paste-btn:active {
  background: #FF8F00;
  transform: translateY(1px);
}

.paste-text {
  color: white;
}

.submit-section {
  
}

.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #FFB800 0%, #FF8F00 100%);
  color: white;
  border: none;
  border-radius: 12px;
  padding: 16px;
  font-size: 18px;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:active {
  transform: translateY(2px);
  box-shadow: 0 2px 8px rgba(255, 184, 0, 0.3);
}

.btn-disabled {
  background: #ccc !important;
  box-shadow: none !important;
  transform: none !important;
}

.submit-text {
  color: white;
}

/* 历史记录 */
.history-card {
  margin: 20px 16px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #FFE082;
}

.history-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.history-count {
  font-size: 12px;
  color: #999;
}

.history-list {
  
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.history-item:last-child {
  border-bottom: none;
}

.history-info {
  flex: 1;
}

.history-order {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  font-family: monospace;
}

.history-time {
  display: block;
  font-size: 12px;
  color: #999;
}

.history-result {
  
}

.result-text {
  font-size: 14px;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
}

.result-text.success {
  color: #4CAF50;
  background: rgba(76, 175, 80, 0.1);
}

.result-text.failed {
  color: #f44336;
  background: rgba(244, 67, 54, 0.1);
}

/* 说明信息 */
.info-card {
  margin: 20px 16px;
}

.info-header {
  margin-bottom: 16px;
}

.info-title {
  font-size: 16px;
  font-weight: bold;
  color: #FFB800;
}

.info-content {
  
}

.info-item {
  display: block;
  font-size: 14px;
  color: #666;
  line-height: 24px;
  margin-bottom: 8px;
}
</style>